# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(impute)
library(tidyverse)

option_list <- list(
  make_option("--config", default = "config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configData <- read_tsv(opt$config) %>%
  set_colnames(c("arg", "value"))
configData

k <- configData %>%
  filter(arg == "knn") %>%
  .$value %>%
  as.numeric()

rate <- configData %>%
  filter(arg == "min") %>%
  .$value %>%
  as.numeric()

replaceMethod <- configData %>%
  filter(arg == "replaceMethod") %>%
  .$value %>%
  as.character()

data <- read_csv("01_AllMet_Raw_Outlier.csv") %>%
  mutate_at(vars(-c("Raw_Metabolite")), function(x) {
    ifelse(x <= 0, NA, x)
  })

if (replaceMethod == "knn") {
  data <- data %>%
    column_to_rownames("Raw_Metabolite") %>%
    as.matrix()
  imData <- impute.knn(data, k)
  print(min(imData[[1]]))
  data <- imData[[1]] %>%
    as.data.frame() %>%
    rownames_to_column("Raw_Metabolite") %>%
    as_tibble()
}else if (replaceMethod == "min") {
  onlyData <- data %>%
    select(-"Raw_Metabolite")
  minValue <- min(onlyData, na.rm = T)
  data <- data %>%
    mutate_at(vars(-"Raw_Metabolite"), function(x) {
      replace_na(x, minValue / rate)
    })
}else if (replaceMethod == "rowMin") {
  onlyData <- data %>%
    select(-"Raw_Metabolite")
  minValue <- min(onlyData, na.rm = T)
  data <- data %>%
    rowwise() %>%
    do({
         result <- as_tibble(.)
         data <- result %>% select(-"Raw_Metabolite") %>% unlist()
         min <- min(data, na.rm = T)
         trueMin <- if (is.infinite(min)) {
           minValue
         }else min
         result %>% mutate_at(vars(-c("Raw_Metabolite")), function(x) {
           replace_na(x, trueMin / rate)
         })
       }) %>%
    ungroup()
}else {
  onlyData <- data %>%
    select(-"Raw_Metabolite")
  b <- any(is.na(onlyData))
  if (b) {
    stop("数据中含有缺失值，无法进一步分析！")
  }
}
outData <- data
outData

write_csv(outData, "02_AllMet_Raw_Missing_Value_Filled.csv")

rawData <- read_csv("02_AllMet_Raw_Missing_Value_Filled.csv")

outData <- rawData %>%
  mutate(Raw_Metabolite = iconv(enc2utf8(Raw_Metabolite), sub = "byte"))

write_csv(outData, "02_AllMet_Raw_Missing_Value_Filled.txt")








